using Services;
using UnityEngine;
using UnityEngine.UI;

public class HUD_EPBar : MonoBehaviour
{
    private Player player;
    private float fillAmount;

    private Image bar;
    private Text text;
    private LinearTransformation linear_bar;

    private void Awake()
    {
        bar = GetComponent<Image>();
        text = GetComponentInChildren<Text>();
        linear_bar = new LinearTransformation();
        linear_bar.Tick += SetFillAmount;
    }

    private void Start()
    {
        player = ServiceLocator.Get<ActionController>().player;
        player.EPChange += OnEPChange;
        player.StatusChange += OnStatusChange;
        text.text = $"{Mathf.Round(player.EnergyPoint)}/{player.data.maxEP}";
    }

    private void OnEPChange(float current, float max, float _)
    {
        text.text = $"{Mathf.Round(current)}/{max}";
        fillAmount = current / max;
        if (fillAmount != bar.fillAmount)
            linear_bar.Initialize(bar.fillAmount, fillAmount, 0.5f);
    }

    private void OnStatusChange()
    {
        text.text = $"{Mathf.Round(player.EnergyPoint)}/{player.data.maxEP}";
        if (player.data.maxEP != 0)
        {
            fillAmount = player.EnergyPoint / player.data.maxEP;
            if (fillAmount != bar.fillAmount)
                linear_bar.Initialize(bar.fillAmount, fillAmount, 0.5f);
        }
    }

    private void SetFillAmount(float value)
    {
        bar.fillAmount = value;
    }
}
